﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Caching;
using System.Web;
using System.Collections;

namespace Cat.Domain.Caching
{
    public class ApplicationCacheManager : ICacheManager
    {
        protected Cache CurrentCache
        {
            get
            {
                Cache cache = null;
                HttpContext current = HttpContext.Current;
                if (current != null)
                {
                    cache = current.Cache;
                }
                else
                {
                    cache = HttpRuntime.Cache;
                }
                return cache;
            }
        }

        #region ICacheManager Members

        public T Get<T>(string key)
        {
            return (T)CurrentCache[key];
        }

        public void Set(string key, object data)
        {
            Set(key, data, 60);
        }

        public void Set(string key, object data, int cacheTime)
        {
            if (data != null)
            {
                Remove(key);
                CurrentCache.Insert(key, data, null, DateTime.Now + TimeSpan.FromMinutes(cacheTime),
                    TimeSpan.Zero, CacheItemPriority.AboveNormal, null);
            }
        }

        public bool IsSet(string key)
        {
            var items = CurrentCache.GetEnumerator();

            return false;
        }

        public void Remove(string key)
        {
            CurrentCache.Remove(key);
        }

        public void RemoveByPattern(string pattern)
        {
            Remove(pattern);
        }

        public void Clear()
        {
            IDictionaryEnumerator enumerator = CurrentCache.GetEnumerator();

            while (enumerator.MoveNext())
            {
                CurrentCache.Remove(enumerator.Key.ToString());
            }
        }

        #endregion
    }
}
